// ==UserScript==
// @name        Notice Search
// @namespace   Violentmonkey Scripts
// @version     20190809
// @match       http://ew.ccs.org.cn/ccsewwms2007/displayViewExternalTopListCommonInfo.do*
// @match       http://expert.ccs.org.cn/header.jsp?id=*
// @updateURL   https://gitee.com/last2003/notice/raw/master/notice.js
// @downloadURL https://gitee.com/last2003/notice/raw/master/notice.js
// @require     http://last2003.gitee.io/lib/l.js
// @resource    data https://gitee.com/last2003/notice/raw/master/notice.json
// @resource    content https://gitee.com/last2003/notice/raw/master/content.html
// @grant       unsafeWindow
// @grant       GM_openInTab
// @grant       GM_setValue
// @grant       GM_getValue
// @grant       GM_deleteValue
// @grant       GM_getResourceText
// @grant       GM_xmlhttpRequest
// @connect     cdn.90so.net
// @connect     gitee.com
// @run-at      document-end
// ==/UserScript==

(function () {
    //code here

    function main_1() {
        ljs
            .addAliases({
                pub:[
                    "https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js",
                    "http://last2003.gitee.io/lib/typeahead.bundle.min.1.js",
                    "http://last2003.gitee.io/lib/handlebars.min.js",
                    "http://last2003.gitee.io/lib/layui/layui.all.js",
                    "http://last2003.gitee.io/lib/layui/css/layui.css",
                ],
                my:[
                    "https://gitee.com/last2003/notice/raw/master/main.js",
                ]
            })
            .onError(function(url) {
                console.log('error loading', url); // <- will print "error loading missingFile.js"
            })
            .load(['pub','my'],function () {
            ;
            ! function () {
                debugger;
                var layer = layui.layer;

                //主要界面函数
                initOrUpdate();
                add2Page();



                ////////////////////////////////////////////函数////////////////////////////////////////////
                function add2Page() {
                    $('body > table:nth-child(1) > tbody > tr:nth-child(1) > td:nth-child(3) > a').click(function (e) {
                        //主要显示区域
                        showSearch();
                        //阻止调用
                        e.preventDefault();
                    });
                   
                }

                function showSearch() {
                    debugger;
                    layer.open({
                        type: 1,
                        title: false,
                        closeBtn: false,
                        shadeClose: true,
                        maxWidth: 10000,
                        area: ['90%', '80%'],
                        offset: ['30px', '30px'],
                        fixed:true,
                        skin: 'fly-layer-search',
                        content:GM_getResourceText('content'),
                        success: function (layero) {
                            $(layero).find('.layui-input')[0].focus();
                            main(layero,GM_getValue('RECORDS'));
                        }
                    });
                }


                //初始化数据
                function initData() {
                    //获取初始化数据
                    var notice_data = JSON.parse(GM_getResourceText('data'));
                    if (notice_data['UPDATE'] != undefined) {
                        GM_setValue('UPDATE', notice_data['UPDATE']);
                    }
                    if (notice_data['RECORDS'] != undefined) {
                        saveRecord(notice_data['RECORDS']);
                    }
                    layer.msg('初始化数据成功！')

                }

                //更新数据
                function updateDate(startDate='',page=1) {

                    _getpage(startDate,page).then(function(reslist){
                        if (GM_getValue('RECORDS') != undefined) {
                            saveRecord(GM_getValue('RECORDS').concat(reslist) );
                            GM_setValue('UPDATE',(new Date()).toISOString().slice(0,10));
                            layer.msg('更新数据成功！ ('+reslist.length+'条)');
                        }
                    });
                    
                    
                    function _getpage(startDate,page,res=[]) {
                        
                        var url='http://ew.ccs.org.cn/ccsewwms2007/displayExternalSearchViewCommonInfo.do?view=1&sortId=&classId=&title=&bpublic=&summary=&endTime=&deptId=&serialId=&stateId=&version=&fileStateId=&language=zh-cn&crmGcSpcode=&crmGcSpname=&crmGcStateId=&crmGcStateName=&crmGcStateEnName=&crmGcclientTypeId=&crmGcclientTypeName=&startTime=';
                        url+=startDate;
                        url+='&page='+page;
    
                        return $.get(url)
                        .then(function(data,status){
                            var response = $('<html />').html(data);
                            //获取本页数据
                            var trs=response.find('#tableColor > tbody > tr')
                            for (let i = 1; i < trs.length; i++) {
                                var d={'id':''};
                                var tds = $(trs[i]).find('td');
                                d['valid']=$(tds[1]).text().trim();
                                d['title']=$(tds[2]).text().trim();
                                d['code']=$(tds[3]).text().trim();
                                d['class_']=$(tds[4]).text().trim();
                                d['type_']=$(tds[5]).text().trim();
                                d['open_']=$(tds[6]).text().trim();
                                d['release']=$(tds[7]).text().trim();
                                d['note_id']=$(tds[1]).attr('onclick').replace("javascript:window.location.href='/ccsewwms2007/displayViewCommonInfo.do?id=",'').replace(/'/,'');
                                //存入结果
                                res.push(d);
                            }
                            //获取总页数
                            var totalPage=parseInt(response.find('span.blank').text().replace('/',''));
                            if (page===totalPage) {
                                return res;
                            }else if(page<totalPage){
                                console.log('next page')
                                return _getpage(startDate,page+1,res);

                            }else{
                                return []
                            }

                            
                        });
                    }
 
                }

                //更新或初始化数据
                function initOrUpdate() {
                    layer.msg('插件运行成功！')
                    var last = GM_getValue('UPDATE');
                    if (last === undefined || last===null) {
                        initData();
                        updateDate(GM_getValue('UPDATE'));
                        return;
                    }
                    if(compareDate(new Date(),new Date(last))>0){
                        var last_next=new Date(last);
                        last_next.setDate(last_next.getDate()+1);
                        updateDate(last_next.toISOString().slice(0,10));
                        return;
                    }
                }

                //比较2个日期大小
                function compareDate(d1,d2) {
                    d1.setHours(0,0,0,0);
                    d2.setHours(0,0,0,0);
                    return d1.getTime()-d2.getTime()
                }

                function saveRecord(rescords) {
                    rescords.sort(function(a,b){
                        return compareDate(new Date(b['release']),new Date(a['release']))//逆序
                    });
                    GM_setValue('RECORDS', rescords);
                }
            }();
        });
    }

    //运行主函数
    main_1();

})();